package com.ledi.pay.exception;

import java.util.Locale;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import com.ledi.pay.utill.ErrorTip;

@RestControllerAdvice
@Slf4j
public class ExceptionResolver {

	@Resource
	private MessageSource messageSource;

	/**
	 * 应用逻辑异常处理
	 *
	 * @see SysCodeController
	 * @param e
	 *            {code:错误码,message:错误编号}
	 * @return
	 */
	@ExceptionHandler(AppCheckException.class)
	@ResponseStatus(HttpStatus.OK)
	public ErrorTip appException(AppCheckException e) {

		log.debug(e.getMessage());
		String message = "";
		try {
			message = messageSource.getMessage(e.getMessage(), e.getParam(), Locale.getDefault());
		} catch (NoSuchMessageException e2) {
			message = e.getMessage();
		}
		String code = messageSource.getMessage(e.getCode(), null, Locale.getDefault());
		return new ErrorTip(Integer.parseInt(code), message);
	}

	/**
	 * 应用逻辑异常处理
	 *
	 * @see SysCodeController
	 * @param e
	 *            {code:错误码,message:错误编号}
	 * @return
	 */
	@ExceptionHandler(SystemException.class)
	@ResponseStatus(HttpStatus.OK)
	public ErrorTip systemException(SystemException e) {

		log.debug(e.getMessage());
		String message = "";
		try {
			message = messageSource.getMessage(e.getMessage(), null, Locale.getDefault());
		} catch (NoSuchMessageException e2) {
			message = e.getMessage();
		}
		return new ErrorTip(-1, message);
	}

}
